<template>
  <div class="login-page op-fullscreen">
    <VanNavBar title="请登录" left-text="返回" left-arrow @click-left="onClickLeft" />
    <VanForm class="login-page__form" @submit="onSubmit">
      <VanCellGroup inset>
        <VanField
            v-model="loginForm.userName"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <VanField
            v-model="loginForm.password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </VanCellGroup>
      <div style="margin: 16px">
        <VanButton round block type="primary" native-type="submit">提交</VanButton>
      </div>
      <div style="margin: 16px">
        <VanButton round block type="primary" @click="goToRegister">还没有账号？注册</VanButton>
      </div>
    </VanForm>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import useUserStore from '@/store/modules/user.ts';
import type { loginForm } from '@/api/user/type.ts';

// 获取路由器
let $router = useRouter();

// 登录输入的数据
let loginForm: loginForm = reactive({ userName: '', password: '' });

// pinia仓库
let useStore = useUserStore();

// 返回
const onClickLeft = () => history.back();

const onSubmit = async () => {
  try {
    await useStore.userLogin(loginForm);
    // 跳转到首页
    $router.push('/');
    ElNotification({
      type: 'success',
      message: '登录成功'
    });
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message
    });
  }
};

const goToRegister = () => {
  $router.push('/register');
};
</script>

<style scoped>
.login-page {
  .login-page__form {
    margin-top: 100px;
  }
}
</style>